import { StackActions, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useCallback, useState, useRef, useEffect } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ScrollView,
  TextInput,
  StatusBar,
  Animated,
  Dimensions,
  Platform,
  ActivityIndicator,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Shadow } from 'react-native-shadow-2';

import FastImage from '@d11/react-native-fast-image';
import { FlashList } from '@shopify/flash-list';
import IconBack from '@svgs/icon_header_back.svg';
import IconSearch from '@svgs/icon_search.svg';

import { BusinessAPI } from '@/api/reworkAPI';
import HeaderBar from '@/components/headerBar';
import { RootStackParamList } from '@/types/navigation';
import { pxToVh, pxToVw } from '@/utils/pxToVx';

const { width: SCREEN_WIDTH } = Dimensions.get('window');
const ITEM_WIDTH = Math.floor((SCREEN_WIDTH - pxToVw(56)) / 2);
const ITEM_HEIGHT = pxToVh(230);
const IMAGE_HEIGHT = Math.floor(ITEM_HEIGHT * 0.65);
const CONTENT_HEIGHT = ITEM_HEIGHT - IMAGE_HEIGHT;

// Premium color palette
const COLORS = {
  primary: '#2563EB',
  primaryLight: '#3B82F6',
  primaryDark: '#1E40AF',
  secondary: '#6366F1',
  accent: '#8B5CF6',
  background: '#FCFCFF',
  card: '#FFFFFF',
  text: '#1E293B',
  textLight: '#475569',
  textMuted: '#94A3B8',
  border: '#E2E8F0',
  borderLight: '#F1F5F9',
  shadow: 'rgba(0, 0, 20, 0.05)',
  gradient1: '#3B82F6',
  gradient2: '#2563EB',
  gradient3: '#1E40AF',
  gradientLight1: '#EFF6FF',
  gradientLight2: '#DBEAFE',
};

const SelectCelebrity = () => {
  const insets = useSafeAreaInsets();
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const [activeCategory, setActiveCategory] = useState<string>('All');
  const [searchText, setSearchText] = useState<string>('');

  // Animation values
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const scaleAnim = useRef(new Animated.Value(0.97)).current;

  // State for celebrities and pagination
  const [celebrities, setCelebrities] = useState<Face.Celebrity[]>([]);
  const [refreshing, setRefreshing] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [lastId, setLastId] = useState<string | undefined>(undefined);

  // Function to fetch celebrities
  const fetchCelebrities = useCallback(async () => {
    try {
      setLoading(true);
      const res = await BusinessAPI.getTemplates(lastId ? { nextId: lastId } : {});
      if (res.code === 0) {
        const data = res.data;
        if (data.records) {
          if (data.records.length === 0) {
            setHasMore(false);
          } else {
            setCelebrities((prev) => (lastId ? [...prev, ...data.records] : data.records));
            if (data.records.length > 0) {
              setLastId(data.records[data.records.length - 1].id);
            }
          }
        }
      } else {
        console.log('Error fetching celebrities');
      }
    } catch (error) {
      console.error('Failed to fetch celebrities:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [lastId]);

  // Handle refresh (pull down)
  const handleRefresh = useCallback(() => {
    setRefreshing(true);
    setLastId(undefined);
    setHasMore(true);
    setCelebrities([]);
    refreshCelebrities();
  }, []);

  // Separate function to fetch initial data without lastId dependency
  const refreshCelebrities = useCallback(async () => {
    try {
      const res = await BusinessAPI.getTemplates({});
      if (res.code === 0) {
        const data = res.data;
        if (data.records) {
          if (data.records.length === 0) {
            setHasMore(false);
          } else {
            setCelebrities(data.records);
            if (data.records.length > 0) {
              setLastId(data.records[data.records.length - 1].id);
            }
          }
        }
      } else {
        console.log('Error fetching celebrities');
      }
    } catch (error) {
      console.error('Failed to fetch celebrities:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  // Handle loading more (pull up)
  const handleLoadMore = useCallback(() => {
    if (!loading && hasMore) {
      fetchCelebrities();
    }
  }, [loading, hasMore, fetchCelebrities]);

  // Animate component mount
  useEffect(() => {
    // Fade and scale in the main screen
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
      Animated.timing(scaleAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
    ]).start();

    // Initial data fetch using the refresh function without lastId
    refreshCelebrities();
  }, []);

  // Filter celebrities based on category and search
  const filteredCelebrities = celebrities.filter((celebrity) => {
    const matchesCategory = activeCategory === 'All' || celebrity.name === activeCategory;
    const matchesSearch = searchText === '' || celebrity.name.toLowerCase().includes(searchText.toLowerCase());

    return matchesCategory && matchesSearch;
  });

  const handleSelectCelebrity = useCallback(
    (celebrity: Face.Celebrity) => {
      // In a real application, you would do something with the selected celebrity
      console.log('Selected celebrity:', celebrity.id);

      navigation.navigate('EnterText', { celebrity });
    },
    [navigation],
  );

  // Render item for FlashList
  const renderCelebrityItem = useCallback(
    ({ item }: { item: Face.Celebrity }) => (
      <View style={styles.celebrityItemContainer}>
        <Shadow distance={12} startColor={COLORS.shadow} style={styles.celebrityItemShadow} offset={[0, 4]}>
          <TouchableOpacity
            style={styles.celebrityItem}
            onPress={() => handleSelectCelebrity(item)}
            activeOpacity={0.9}
          >
            <View style={styles.celebrityImageContainer}>
              <FastImage source={{ uri: item.avtarUrl }} style={styles.celebrityImage} resizeMode="cover" />
              <LinearGradient
                colors={['transparent', 'rgba(30, 41, 59, 0.5)']}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.celebrityImageOverlay}
              />
            </View>
            <View style={styles.celebrityContent}>
              <View style={styles.celebrityTextContainer}>
                <Text style={styles.celebrityName} numberOfLines={1}>
                  {item.name}
                </Text>
                <Text style={styles.celebrityDescription} numberOfLines={1}>
                  {item.description}
                </Text>
              </View>
            </View>
          </TouchableOpacity>
        </Shadow>
      </View>
    ),
    [handleSelectCelebrity],
  );

  // Render footer for the list (loading indicator)
  const renderFooter = useCallback(() => {
    if (!loading || refreshing) return null;
    return (
      <View style={styles.footerLoader}>
        <ActivityIndicator size="small" color={COLORS.primary} />
        <Text style={styles.footerText}>Loading more...</Text>
      </View>
    );
  }, [loading, refreshing]);

  return (
    <Animated.View
      style={[
        styles.container,
        {
          paddingTop: insets.top,
          opacity: fadeAnim,
          transform: [{ scale: scaleAnim }],
        },
      ]}
    >
      <StatusBar backgroundColor={COLORS.background} barStyle="dark-content" />

      {/* Header */}
      <HeaderBar title="Select Celebrity" leftIcon={<IconBack />} />

      {/* Search Input */}
      <Animated.View style={[styles.searchContainer, { opacity: fadeAnim }]}>
        <Shadow distance={8} startColor={COLORS.shadow} style={styles.searchShadow}>
          <View style={styles.searchInputContainer}>
            <View style={styles.searchIconContainer}>
              <IconSearch width={18} height={18} color={COLORS.textLight} />
            </View>
            <TextInput
              style={styles.searchInput}
              placeholder="Search celebrities..."
              placeholderTextColor={COLORS.textMuted}
              value={searchText}
              onChangeText={setSearchText}
            />
          </View>
        </Shadow>
      </Animated.View>

      {/* Category Tabs */}
      <Animated.View style={[styles.categoryTabsContainer, { opacity: fadeAnim }]}>
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          style={styles.categoryTabs}
          contentContainerStyle={styles.categoryTabsContent}
        >
          {['All', 'Business', 'Entertainment', 'Sports'].map((category) => (
            <TouchableOpacity
              key={category}
              style={[styles.categoryTab]}
              onPress={() => setActiveCategory(category)}
              activeOpacity={0.7}
            >
              {activeCategory === category ? (
                <View style={styles.categoryTabActive}>
                  <Text style={styles.activeCategoryTabText}>{category}</Text>
                </View>
              ) : (
                <View style={styles.categoryTabInactive}>
                  <Text style={styles.categoryTabText}>{category}</Text>
                </View>
              )}
            </TouchableOpacity>
          ))}
        </ScrollView>
      </Animated.View>

      {/* Celebrity Grid using FlashList */}
      <View style={styles.flashListContainer}>
        <FlashList
          data={filteredCelebrities}
          renderItem={renderCelebrityItem}
          estimatedItemSize={ITEM_HEIGHT}
          numColumns={2}
          showsVerticalScrollIndicator={false}
          contentContainerStyle={styles.flashListContent}
          onRefresh={handleRefresh}
          refreshing={refreshing}
          onEndReached={handleLoadMore}
          onEndReachedThreshold={0.5}
          ListFooterComponent={renderFooter}
          ListEmptyComponent={
            <View style={styles.emptyContainer}>
              <Text style={styles.emptyText}>{loading ? 'Loading...' : 'No celebrities found'}</Text>
            </View>
          }
        />
      </View>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: pxToVw(20),
    paddingVertical: pxToVh(14),
    zIndex: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 10,
    borderBottomWidth: 0.3,
    borderBottomColor: 'rgba(203, 213, 225, 0.6)',
  },
  backButton: {
    width: pxToVw(44),
    height: pxToVw(44),
    borderRadius: pxToVw(22),
    backgroundColor: COLORS.gradientLight1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerTitleContainer: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  headerTitle: {
    fontSize: pxToVh(18),
    fontWeight: '700',
    color: COLORS.text,
    letterSpacing: -0.5,
  },
  placeholder: {
    width: pxToVw(44),
  },
  searchContainer: {
    paddingHorizontal: pxToVw(22),
    marginTop: pxToVh(16),
    marginBottom: pxToVh(22),
  },
  searchShadow: {
    width: '100%',
    borderRadius: pxToVw(18),
  },
  searchInputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: COLORS.card,
    paddingHorizontal: pxToVw(18),
    paddingVertical: pxToVh(14),
    borderRadius: pxToVw(18),
    borderWidth: 1,
    borderColor: 'rgba(241, 245, 249, 0.8)',
  },
  searchIconContainer: {
    marginRight: pxToVw(12),
    opacity: 0.8,
  },
  searchIcon: {
    tintColor: COLORS.textLight,
  },
  searchInput: {
    flex: 1,
    fontSize: pxToVh(15),
    color: COLORS.text,
    padding: 0,
    fontWeight: '400',
  },
  categoryTabsContainer: {
    paddingVertical: pxToVh(8),
    marginBottom: pxToVh(16),
  },
  categoryTabs: {
    flexDirection: 'row',
  },
  categoryTabsContent: {
    paddingHorizontal: pxToVw(22),
    paddingVertical: pxToVh(8),
  },
  categoryTab: {
    marginRight: pxToVw(12),
    borderRadius: 20,
    overflow: 'hidden',
  },
  categoryTabActive: {
    paddingVertical: pxToVh(12),
    paddingHorizontal: pxToVw(22),
    borderRadius: 20,
    backgroundColor: COLORS.primary,
  },
  categoryTabInactive: {
    paddingVertical: pxToVh(12),
    paddingHorizontal: pxToVw(22),
    borderRadius: 20,
    backgroundColor: 'rgba(241, 245, 249, 0.7)',
    borderWidth: 1,
    borderColor: 'rgba(226, 232, 240, 0.8)',
  },
  categoryTabText: {
    fontSize: pxToVh(14),
    fontWeight: '500',
    color: COLORS.textLight,
    textAlign: 'center',
  },
  activeCategoryTabText: {
    fontSize: pxToVh(14),
    fontWeight: '600',
    color: COLORS.card,
    textAlign: 'center',
  },
  flashListContainer: {
    flex: 1,
    marginHorizontal: pxToVw(18),
  },
  flashListContent: {
    paddingHorizontal: pxToVw(4),
    paddingBottom: pxToVh(20),
  },
  celebrityItemContainer: {
    width: ITEM_WIDTH,
    height: ITEM_HEIGHT,
    marginHorizontal: pxToVw(4),
    marginBottom: pxToVh(24),
  },
  celebrityItemShadow: {
    borderRadius: pxToVw(22),
    height: '100%',
  },
  celebrityItem: {
    borderRadius: pxToVw(22),
    overflow: 'hidden',
    backgroundColor: COLORS.card,
    height: '100%',
  },
  celebrityImageContainer: {
    position: 'relative',
    width: '100%',
    height: IMAGE_HEIGHT,
  },
  celebrityImage: {
    width: '100%',
    height: '100%',
  },
  celebrityImageOverlay: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    height: '40%',
  },
  celebrityContent: {
    padding: pxToVw(12),
    paddingBottom: pxToVw(10),
    flex: 1,
    justifyContent: 'center',
    height: CONTENT_HEIGHT,
  },
  celebrityTextContainer: {
    flex: 1,
    justifyContent: 'center',
  },
  celebrityName: {
    fontSize: pxToVh(15),
    fontWeight: '700',
    color: COLORS.text,
    letterSpacing: -0.5,
  },
  celebrityDescription: {
    fontSize: pxToVh(12),
    color: COLORS.textLight,
    marginTop: pxToVh(2),
  },
  categoryPill: {
    alignSelf: 'flex-start',
    backgroundColor: COLORS.gradientLight1,
    paddingHorizontal: pxToVw(10),
    paddingVertical: pxToVh(4),
    borderRadius: 20,
    marginTop: pxToVh(8),
  },
  categoryPillText: {
    fontSize: pxToVh(11),
    fontWeight: '500',
    color: COLORS.primary,
  },
  emptyContainer: {
    flex: 1,
    height: pxToVh(200),
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyText: {
    fontSize: pxToVh(16),
    color: COLORS.textLight,
  },
  footerLoader: {
    paddingVertical: pxToVh(20),
    alignItems: 'center',
  },
  footerText: {
    fontSize: pxToVh(14),
    color: COLORS.textLight,
    marginTop: pxToVh(8),
  },
});

export default SelectCelebrity;
